<template>
  <el-dialog :title="info.isadd ? '添加商品规格' : '添加商品规格'" :visible.sync="info.isshow" center>
    <el-form :model="specsinfo" :rules="rules" ref="form">
      <el-form-item label="规格名称" label-width="120px" prop="specsname">
        <el-input v-model="specsinfo.specsname"></el-input>
      </el-form-item>
      <el-form-item
        label="规格属性"
        label-width="120px"
        v-for="(item,index) in specsArr"
        :key="item.id"
      >
        <el-input v-model="item.value" class="attr-in"></el-input>
        <el-button type="primary" @click="addspecsArr" v-if="index == 0">添加规格属性</el-button>
        <el-button v-else @click="delspecsArr(index)">删除</el-button>
      </el-form-item>
      <el-form-item label="状态" label-width="120px">
        <el-switch
          v-model="specsinfo.status"
          active-color="#13ce66"
          inactive-color="#ccc"
          :active-value="1"
          :inactive-value="2"
        ></el-switch>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="sure">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters,mapActions } from 'vuex';
import {specsadd,specsinfo,specsedit} from "@/request/api.js"
export default {
  props: ["info"],
  data() {
    return {
      //商品规格数据
      specsinfo: {
        specsname: "", //商品规格名称 string
        attrs: "", //商品规格属性值（必填，否则获取时报错）string "白色,红色，黄色"
        status: 1 //状态1正常2禁用number1
      },

      //商品规格属性属性
      specsArr: [{ id: Math.random(), value: "" }],
      //定义表单规则
      rules: {
        specsname: [
          { required: true, message: "请输入规格名称", trigger: "blur" },
          { min: 2, max: 12, message: "长度在 2 到 12 个字符", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    ...mapActions("specs",["action_specsList"]), //获取商品规格数据的方法
    //1.取消  -- 通知父组件，关闭弹框
    cancel() {
      this.$emit("cancel");
      this.reset();
    },
    reset(){
       //商品规格数据
       this.specsinfo = {
        specsname: "", //商品规格名称 string
        attrs: "", //商品规格属性值（必填，否则获取时报错）string "白色,红色，黄色"
        status: 1 //状态1正常2禁用number1
      };

      //商品规格属性属性
      this.specsArr = [{ id: Math.random(), value: "" }];

      this.$refs.form.clearValidate();
    },
    //2.点击确定
    sure() {
      //表单验证能通过就提交
      this.$refs.form.validate(async val => {
        if (!val) {
          return;
        }

        // console.log(this.specsinfo); //attrs:"" 没有值，
        // console.log(this.specsArr);  //用的是specsArr绑定的标签，所以数据都在specsArr里面
        // let arr = this.specsArr.map(item=>{
        //   return item.value
        // });
        // console.log(arr); //["1","2","3"]
        // console.log(arr.join(",")); //数组转换为字符串  "1,2,3"
        // return;

        //添加
        if (this.info.isadd) {
          try{
            //后端需要attrs是一个字符串 "1,2,3"
            this.specsinfo.attrs = this.specsArr.map(item=>item.value).join(",");
            let res = await specsadd(this.specsinfo);
            if(res.code == 200){
              //提示，关闭弹窗 ,重新获取数据渲染页面
              this.$message.success(res.msg);
              this.cancel();
              this.action_specsList();
            }else{
              this.$message.info(res.msg)
            }

          }catch(err){
            this.$message.error(err)
          }

        } else {
          console.log("编辑");
        }
      
      });
    },
    //3.点击规格属性,点击就添加一项
    addspecsArr() {
      this.specsArr.push({ id: Math.random(), value: "" });
    },
    //4.点击删除规格属性
    delspecsArr(index) {
      this.specsArr.splice(index, 1);
    },
    //5.回显数据
    async lookup(id){
      try{
        let res = await specsinfo({id});
        if(res.code == 200){

          // //赋值数据，回显
          this.specsinfo = res.list[0];
          // //添加id字段
          this.specsinfo.id = id;
          //回显规格属性        ["红色","绿色","黄色"]
          this.specsArr = this.specsinfo.attrs.map(item=> ({id:Math.random(),value:item}) )

        }else{
          this.$message.info(res.msg);
        }
      }catch(err){
        this.$message.error(err);
      }
    }
  }
};
</script>

<style scoped>
.attr-in {
  width: 65%;
  margin-right: 5px;
}
</style>